<script setup lang="ts">
  import { getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'
  import { reqMenuAddUrl, reqMenuEditUrl } from '@/api/system/menu'
  import { NodeType } from '@/api/system/menu/type.ts'
  import { ElMessage } from 'element-plus'
  import { Search } from '@element-plus/icons-vue'
  import SvgIcon from '@/components/SvgIcon/index.vue'
  import SelectSvgIcon from '@/components/SelectSvgIcon/index.vue'

  /*获取父组件传递来的信息*/
  const props = defineProps({
    menuOptions: {
      // 菜单树选项
      type: [],
      default: [],
      required: true,
    },
  })

  const open = ref(false) // 是否显示弹出层
  const title = ref('新增菜单')
  const dialogVisible = ref(false)
  const formFormRef = ref()
  /*表单数据*/
  const ruleForm = reactive({
    menuId: undefined,
    parentId: 0,
    menuType: 'M',
    icon: '',
    menuName: undefined,
    orderNum: '0' /*显示排序*/,
    isFrame: '1' /*是否外链*/,
    path: '' /*路由地址*/,
    component: '' /*组件路径*/,
    perms: '' /*权限标识*/,
    query: '' /*路由参数*/,
    isCache: '0' /*是否缓存*/,
    visible: '0' /*显示状态*/,
    status: '0' /*菜单状态*/,
  })

  const { proxy }: any = getCurrentInstance()

  let $emit = defineEmits(['handleMenuQuery'])

  /*重置表单*/
  const resetForm = () => {
    ruleForm.menuId = undefined
    ruleForm.parentId = 0
    ruleForm.menuType = 'M'
    ruleForm.icon = ''
    ruleForm.menuName = undefined
    ruleForm.orderNum = '0'
    ruleForm.isFrame = '1'
    ruleForm.path = ''
    ruleForm.component = ''
    ruleForm.perms = '' /*权限标识*/
    ruleForm.query = '' /*路由参数*/
    ruleForm.isCache = '0' /*是否缓存*/
    ruleForm.visible = '0' /*显示状态*/
    ruleForm.status = '0' /*菜单状态*/
  }

  /*新增或者修改信息*/
  const show = async (item: any = {}) => {
    title.value = '新增菜单'
    /*编辑用户的操作*/
    await filterMethod() /*将传进来的部门信息进行过滤*/
    if (item.menuId) {
      title.value = '编辑菜单'
      /*表单赋值*/
      Object.keys(item).forEach((key) => {
        ruleForm[key] = item[key]
      })
    } else {
      ruleForm.parentId = item.parentId
    }
    dialogVisible.value = true
  }
  /*
  onMounted(() => {
    filterMethod() /!*将传进来的部门信息进行过滤*!/
  })

  watch(
    () => props.menuOptions,
    () => {
      filterMethod()
    },
  )*/

  const visibleIcon = ref(false)
  const treeRef = ref()
  const data = ref()
  /*生成节点树*/
  const filterMethod = () => {
    let list: NodeType[] = []
    ;[...props.menuOptions].filter((item: any) => {
      let node: NodeType = {
        value: 0,
        label: '',
        length: 0,
        children: [],
      }
      node.value = item.menuId
      node.label = item.menuName
      node.length = item.children.length == undefined ? 0 : item.children.length
      if (item.children) {
        node.children = getChildMethod(item.children)
      }
      list.push(node)
    })
    data.value = [
      {
        value: 0,
        label: '主类目',
        children: list,
      },
    ]
  }
  const getChildMethod = (item: any) => {
    let child: any = []
    item.filter((it: any) => {
      const node = ref({
        value: undefined,
        length: undefined,
        label: null,
        children: [],
      })
      node.value.value = it.menuId
      node.value.label = it.menuName
      node.value.length = it.children.length
      if (it.children) {
        node.value.children = getChildMethod(it.children)
      }
      child.push(node)
    })
    return child
  }

  /*选择图标*/
  const selected = (name: String) => {
    ruleForm.icon = name
    visibleIcon.value = !visibleIcon.value
  }

  /*提交表单*/
  const submitForm = async () => {
    /*保证全部的表单项校验通过再发请求*/
    if (!formFormRef.value) return
    await formFormRef.value?.validate(async (valid: any, fields: any) => {
      if (valid) {
        let result = null
        if (!ruleForm.menuId) {
          result = await reqMenuAddUrl(ruleForm)
        } else {
          result = await reqMenuEditUrl(ruleForm)
        }
        if (result.code === 200) {
          ElMessage.success(result.message == null ? '添加成功' : result.message)
          handleClose() /*关闭对话框*/
          $emit('handleMenuQuery')
        } else {
          ElMessage.error(result.message == null ? '操作失败' : result.message)
        }
      } else {
        console.log('error submit!', fields)
      }
    })
  }

  const handleClose = () => {
    proxy.$resetForm(formFormRef)
    resetForm() //重置表单
    dialogVisible.value = false
  }

  // 校验表单
  let formRules = reactive({
    menuName: [{ required: true, message: '菜单名称不能为空', trigger: 'change' }],
    orderNum: [{ required: true, message: '菜单顺序不能为空', trigger: 'change' }],
    path: [{ required: true, message: '路由地址不能为空', trigger: 'change' }],
  })

  //主动暴露方法
  defineExpose({ show })
</script>

<script lang="ts">
  export default {
    dicts: ['sys_show_hide', 'sys_normal_disable'],
  }
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    :visible.sync="open"
    @close="handleClose"
    width="680px"
    append-to-body
  >
    <template #title>
      <span class="el-dialog__title">{{ title }}</span>
    </template>
    <el-form :model="ruleForm" ref="formFormRef" label-width="100px" :rules="formRules">
      <el-row>
        <el-col :span="24">
          <el-form-item label="上级菜单" prop="parentId">
            <el-tree-select
              ref="treeRef"
              v-model="ruleForm.parentId"
              :data="data"
              placeholder="请选择上级菜单"
              check-strictly
              clearable
              value-key="value"
              :default-expanded-keys="[ruleForm.parentId]"
              highlight-current
              style="width: 100%"
            >
              <template #default="{ data: { label, length } }">
                <template v-if="length > 0">
                  {{ label }}
                  <span style="color: gray">({{ length }})</span>
                </template>
              </template>
            </el-tree-select>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item label="菜单类型" prop="menuType">
            <el-radio-group v-model="ruleForm.menuType">
              <el-radio label="M">目录</el-radio>
              <el-radio label="C">菜单</el-radio>
              <el-radio label="F">按钮</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>

        <el-col :span="24" v-if="ruleForm.menuType != 'F'">
          <el-form-item label="菜单图标" prop="icon">
            <el-popover placement="bottom-end" trigger="click" width="460">
              <SelectSvgIcon
                v-model="visibleIcon"
                @selected="selected"
                :active-icon="ruleForm.icon"
                visible
              ></SelectSvgIcon>
              <template #reference>
                <el-input
                  @click="visibleIcon = true"
                  v-model="ruleForm.icon"
                  style="width: 90%"
                  placeholder="点击选择图标"
                  readonly
                >
                  <template #prefix>
                    <SvgIcon v-if="ruleForm.icon" slot="prefix" :icon-class="ruleForm.icon" />
                    <el-icon v-else slot="prefix">
                      <Search />
                    </el-icon>
                  </template>
                </el-input>
              </template>
            </el-popover>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="菜单名称" prop="menuName">
            <el-input v-model="ruleForm.menuName" placeholder="请输入菜单名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="显示排序" prop="orderNum">
            <el-input-number v-model="ruleForm.orderNum" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="ruleForm.menuType != 'F'">
          <el-form-item prop="isFrame">
            <template #label>
              <el-tooltip content="选择是外链则路由地址需要以`http(s)://`开头" placement="top">
                <el-icon style="margin-top: 8px;"><QuestionFilled/></el-icon>
              </el-tooltip>
              &nbsp;是否外链
            </template>
            <el-radio-group v-model="ruleForm.isFrame">
              <el-radio label="0">是</el-radio>
              <el-radio label="1">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="ruleForm.menuType != 'F'">
          <el-form-item prop="path">
            <template #label>
              <el-tooltip
                content="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
                placement="top"
              >
                <el-icon style="margin-top: 8px;"><QuestionFilled/></el-icon>
              </el-tooltip>&nbsp;路由地址
            </template>
            <el-input v-model="ruleForm.path" placeholder="请输入路由地址(user)" />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="ruleForm.menuType == 'C'">
          <el-form-item prop="component">
            <template #label>
              <el-tooltip
                content="访问的组件路径，如：`system/user/index`，默认在`views`目录下"
                placement="top"
              >
                <el-icon style="margin-top: 8px;"><QuestionFilled/></el-icon>
              </el-tooltip>
              &nbsp;组件路径
            </template>
            <el-input v-model="ruleForm.component" placeholder="请输入组件路径" />
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="ruleForm.menuType != 'M'">
          <el-form-item prop="perms">
            <el-input v-model="ruleForm.perms" placeholder="请输入权限标识" maxlength="100" />
            <template #label>
              <el-tooltip
                content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPermi('system:user:list')`)"
                placement="top"
              >
                <el-icon style="margin-top: 8px;"><QuestionFilled/></el-icon>
              </el-tooltip>
              &nbsp;权限字符
            </template>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="ruleForm.menuType == 'C'">
          <el-form-item prop="query">
            <el-input v-model="ruleForm.query" placeholder="请输入路由参数" maxlength="255" />
            <template #label>
              <el-tooltip
                content='访问路由的默认传递参数，如：`{"id": 1, "name": "ry"}`'
                placement="top"
              >
                <el-icon style="margin-top: 8px;"><QuestionFilled/></el-icon>
              </el-tooltip>
              &nbsp;路由参数
            </template>
          </el-form-item>
        </el-col>

        <el-col :span="12" v-if="ruleForm.menuType == 'C'">
          <el-form-item prop="isCache">
            <template #label>
              <el-tooltip
                content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"
                placement="top"
              >
                <el-icon style="margin-top: 8px;"><QuestionFilled/></el-icon>
              </el-tooltip>
              &nbsp;是否缓存
            </template>
            <el-radio-group v-model="ruleForm.isCache">
              <el-radio label="0">缓存</el-radio>
              <el-radio label="1">不缓存</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="ruleForm.menuType != 'F'">
          <el-form-item prop="visible">
            <template #label>
              <el-tooltip
                content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                placement="top"
              >
                <el-icon style="margin-top: 8px;"><QuestionFilled/></el-icon>
              </el-tooltip>
              &nbsp;显示状态
            </template>
            <el-radio-group v-model="ruleForm.visible">
              <el-radio
                v-for="dict in dict.type.sys_show_hide"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="ruleForm.menuType != 'F'">
          <el-form-item prop="status">
            <template #label>
              <el-tooltip content="选择停用则路由将不会出现在侧边栏，也不能被访问" placement="top">
                <el-icon style="margin-top: 8px;"><QuestionFilled/></el-icon>
              </el-tooltip>
              &nbsp;菜单状态
            </template>
            <el-radio-group v-model="ruleForm.status">
              <el-radio
                v-for="dict in dict.type.sys_normal_disable"
                :key="dict.value"
                :label="dict.value"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="success" @click="submitForm">提交</el-button>
        <el-button type="warning" @click="dialogVisible = false">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
  @import './../index';
  /*红色星号样式*/
  .must-tip {
    margin-right: 5px;
    color: red;
  }
</style>
